package com.zhoust.fastdome.adapter;

import com.alibaba.fastjson.JSONObject;
import com.zhoust.fastdome.business.service.CommonLogService;
import com.zhoust.fastdome.common.CommonConstant;
import com.zhoust.fastdome.utils.MyRequestUtils;
import com.zhoust.fastdome.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhoust
 * @Date 2021/9/23 8:50
 * @Desc 日志前置拦截器
 * 在项目中使用，可以有两种方式，选择实现HandlerInterceptor接口或者继承HandlerInterceptorAdapter类
 */
@Slf4j
@Component
public class LogInterceptor implements HandlerInterceptor{
    @Value("${fast.dome.logType}")
    private String logType;
    private final CommonLogService commonLogService;

    public LogInterceptor(CommonLogService commonLogService) {
        this.commonLogService = commonLogService;
    }

    /**
     * 前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!CommonConstant.adapter.equals(logType)){
            return true;
        }
        //通过前置拦截器获取请求数据（如果是地址栏参数从parameter中获取，其他的从body中获取，另外还有地址栏跟body中都有的，这种变态报文尽量在定义接口的时候就杜绝掉）
        String logId = String.valueOf(SnowflakeIdWorker.generateId());
        request.setAttribute("logId",logId);
        commonLogService.saveLogByHandler(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if(!CommonConstant.adapter.equals(logType)){

        }else{
            log.info("后置处理器开始");
            Object responseBody = request.getAttribute("responseBody");
            String s = JSONObject.toJSONString(responseBody);
            commonLogService.updateLogByHandler(request,s);
            HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
        }
    }

}
